package com.wisdytech.linkdcs.tool.service.impl;

import com.github.pagehelper.PageInfo;
import com.wisdytech.common.bean.Filter;
import com.wisdytech.common.constants.CommonConstants;
import com.wisdytech.common.constants.DictKeyConstants;
import com.wisdytech.common.enums.ToolRepairStatus;
import com.wisdytech.common.enums.ToolRepairType;
import com.wisdytech.common.enums.ToolStatus;
import com.wisdytech.common.exception.ServiceException;
import com.wisdytech.common.handler.BaseService;
import com.wisdytech.common.utils.BaseUtil;
import com.wisdytech.linkdcs.system.model.SysUser;
import com.wisdytech.linkdcs.tool.dao.ToolRepairApprovalDao;
import com.wisdytech.linkdcs.tool.dao.ToolRepairDao;
import com.wisdytech.linkdcs.tool.dao.TtEqToolDao;
import com.wisdytech.linkdcs.tool.model.ToolRepair;
import com.wisdytech.linkdcs.tool.model.ToolRepairApproval;
import com.wisdytech.linkdcs.tool.model.TtEqTool;
import com.wisdytech.linkdcs.tool.service.IToolRepairService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhanghailin
 * @since 2018-06-14
 */
@Service
@Transactional
public class ToolRepairServiceImpl extends BaseService<ToolRepairDao, ToolRepair> implements IToolRepairService {

    @Resource
    private ToolRepairDao toolRepairDao;

    @Resource
    private TtEqToolDao ttEqToolDao;

    /**
     * 所有维修记录都存在tt_eq_tool_repair表中，只保存维修信息和tool_code
     * 维修状态和维修类型存在tt_eq_tool中
     * 查询以tt_eq_tool_repair为主表左连接tt_eq_tool表，根据tool表中的repair_status 和repair_type 筛选记录
     *
     * @param toolCode   编码
     * @param toolName   名称
     * @param toolType   类型
     * @param toolStatus 列表查询条件
     * @param equipCode  设备
     * @param filter     分页
     * @return 分页结果
     */
    @Override
    public PageInfo<ToolRepair> getToolRepairByFilter(String toolCode, String toolName, String toolType, String toolModel,String toolStatus, String equipCode, Filter filter) {
        Map<String, Object> params = new HashMap<>();
        params.put("toolTypeParentKey", DictKeyConstants.TOOL_TYPE_PARENT_KEY);
        if (StringUtils.isNotBlank(toolCode)) {
            params.put("toolCode", toolCode);
        }
        if (StringUtils.isNotBlank(toolName)) {
            params.put("toolName", toolName);
        }
        if (StringUtils.isNotBlank(toolType)) {
            params.put("toolType", toolType);
        }
        if (StringUtils.isNotBlank(toolModel)) {
            params.put("toolModel", toolModel);
        }
        if (StringUtils.isNotBlank(equipCode)) {
            params.put("equipCode", equipCode);
        }

        //厂内维修列表
        if ("1".equals(toolStatus)) {
            //维修类型为厂内维修
            params.put("repairType", ToolRepairType.REPAIR_IN_FACTORY.getCode());
            //维修状态为待维修
            params.put("toolRepairStatus", ToolRepairStatus.NEED_REPAIR.getCode());
        }
        //委外维修列表
        else if ("2".equals(toolStatus)) {
            //维修类型为委外维修
            params.put("repairType", ToolRepairType.DELAGATION.getCode());
        }
        //已维修列表
        else if ("3".equals(toolStatus)) {
            //维修状态为已维修
            params.put("toolRepairStatus", ToolRepairStatus.REPAIRED.getCode());
        }
        //已报废列表
        else if ("4".equals(toolStatus)) {
            //维修状态为已报废
            params.put("toolRepairStatus", ToolRepairStatus.SCRAPED.getCode());
            // TODO
            List<ToolRepair> list = this.beforeList(ToolRepairDao.class, filter).getToolListByFilter(params);
            return new PageInfo<>(list);
        }
        List<ToolRepair> list = this.beforeList(ToolRepairDao.class, filter).getToolRepairByFilter(params);
        return new PageInfo<>(list);
    }

    @Override
    public Boolean repair(ToolRepair toolRepair, SysUser operator) {
        if (operator == null)
            throw new ServiceException("操作人不能为空");
        if (toolRepair == null || StringUtils.isBlank(toolRepair.getPkId())) {
            throw new ServiceException("参数错误");
        }
        Integer count = this.toolRepairDao.updateById(toolRepair);
        //更新工装维修状态为已维修，工装状态为可使用
        if (count > 0) {
            TtEqTool tool = new TtEqTool();
            tool.setStatus(ToolStatus.USABLE.getCode());
            tool.setRepairStatus(ToolRepairStatus.REPAIRED.getCode());
            //TODO nullpointexception check
            tool.setToolCode(toolRepairDao.selectById(toolRepair.getPkId()).getToolCode());
            ttEqToolDao.updateStatusByToolCode(tool);
        }
        return count > 0;
    }

    @Resource
    private ToolRepairApprovalDao toolRepairApprovalDao;

    @Override
    public Boolean sendPepair(ToolRepair toolRepair, SysUser operator) {
        Optional.ofNullable(operator)
                .orElseThrow(() -> new ServiceException("操作人不能为空"));
        if (toolRepair == null || StringUtils.isBlank(toolRepair.getPkId())) {
            throw new ServiceException("参数错误");
        }
        //TODO 校验工装状态是不是待维修且维修方式委外维修
        Integer count = this.toolRepairDao.updateById(toolRepair);
        //在工装委外维修申请表中加入一条记录，初始状态待审批
        ToolRepairApproval approval = new ToolRepairApproval();
        approval.setPkId(BaseUtil.getUUID());
        approval.setRepairId(toolRepair.getPkId());
        approval.setStatus("1");//待审批
        approval.setCreateDate(new Date());
        approval.setDelFlag(CommonConstants.DEL_FLAG);
        approval.setCreateUser(operator.getUsername());
        toolRepairApprovalDao.insert(approval);
        //更新工装维修状态为已送修，工装状态为不可用
        if (count > 0) {
            TtEqTool tool = new TtEqTool();
            tool.setStatus(ToolStatus.UNAVAILABLE.getCode());
            tool.setRepairStatus(ToolRepairStatus.DELEGATED.getCode());
            tool.setToolCode(Optional.ofNullable(toolRepairDao.selectById(toolRepair.getPkId()))
                    .map(ToolRepair::getToolCode)
                    .orElseThrow(() -> new ServiceException("系统错误")));
            ttEqToolDao.updateStatusByToolCode(tool);
        }
        return count > 0;
    }

    @Override
    public Boolean backFactory(String toolCodes, String pkIds, SysUser operator) {
        if(operator == null)
            throw new ServiceException("操作人不能为空 ");
        String[] backFactoryCodes = toolCodes.split(",");
        if (backFactoryCodes.length==0) return true;
        for (String toolCode:backFactoryCodes) {
            TtEqTool tool = new TtEqTool();
            // 返厂 已维修 可使用
            tool.setStatus(ToolStatus.USABLE.getCode());
            tool.setRepairStatus(ToolRepairStatus.REPAIRED.getCode());
            tool.setToolCode(toolCode);
            //校验返厂的设备工装状态是不是已送修
            if (!ToolRepairStatus.NEED_BACK.getCode().equals(checkToolRepairStatus(toolCode))) {
                throw new ServiceException(toolCode+"的工装状态不是已送修");
            }
            ttEqToolDao.updateStatusByToolCode(tool);
        }
        String[] ids = pkIds.split(",");
        if (ids.length==0) return true;
        for (String pkId:ids) {
            ToolRepair toolRepair = new ToolRepair();
            toolRepair.setBackDate(new Date());
            toolRepair.setPkId(pkId);
            //更新返厂时间
            toolRepairDao.updateById(toolRepair);
        }
        return true;
    }

    @Override
    public Boolean scrap(String toolCodes, SysUser operator) {
        if(operator == null)
            throw new ServiceException("操作人不能为空 ");
        String[] backFactoryCodes = toolCodes.split(",");
        if (backFactoryCodes.length==0) return true;
        for (String toolCode:backFactoryCodes) {
            TtEqTool tool = new TtEqTool();
            // 报废 已报废 不可用
            tool.setStatus(ToolStatus.UNAVAILABLE.getCode());
            tool.setRepairStatus(ToolRepairStatus.SCRAPED.getCode());
            tool.setToolCode(toolCode);
            ttEqToolDao.updateStatusByToolCode(tool);
        }
        return true;
    }

    @Override
    public PageInfo<ToolRepair> findToolRepairApprovalListByPage(String equipCode, String areaId,String shopId,String lineId,String applicationStartDate, String applicationEndDate,Filter filter) {
        Map<String, Object> params = new HashMap<>();
        params.put("toolTypeParentKey", DictKeyConstants.TOOL_TYPE_PARENT_KEY);
        if (StringUtils.isNotBlank(equipCode)) {
            params.put("equipCode", equipCode);
        }
        if (StringUtils.isNotBlank(areaId)) {
            params.put("areaId", areaId);
        }
        if (StringUtils.isNotBlank(shopId)) {
            params.put("shopId", shopId);
        }
        if (StringUtils.isNotBlank(lineId)) {
            params.put("lineId", lineId);
        }
        if (StringUtils.isNotBlank(applicationStartDate)) {
            params.put("applicationStartDate", applicationStartDate);
        }
        if (StringUtils.isNotBlank(applicationEndDate)) {
            params.put("applicationEndDate", applicationEndDate);
        }

        List<ToolRepair> list = this.beforeList(ToolRepairDao.class, filter).selectToolRepairApprovalByFilter(params);
        return new PageInfo<>(list);
    }



    /**
     * 审批完成业务流程
     * 1.直接修改审批记录表中的状态为审批完成
     * 2.修改工装状态为待返厂
     * @param approvalId 审批记录id
     * @param repairId 维修记录id
     */
    @Override
    public void toolRepairApprovalCompletion(String approvalId, String repairId) {
        if (StringUtils.isBlank(approvalId)||StringUtils.isBlank(repairId)) {
            throw new ServiceException("审批记录id为空");
        }
        ToolRepairApproval approval = new ToolRepairApproval();
        approval.setPkId(approvalId);
        //审批完成
        approval.setStatus("0");
        toolRepairApprovalDao.updateById(approval);

        //查询toolCode
        ToolRepair toolRepair = toolRepairDao.selectById(repairId);
        if (toolRepair == null||StringUtils.isBlank(toolRepair.getToolCode())) {
            throw new ServiceException("未找到该条审批记录对应的工装维修记录");
        }
        TtEqTool tool = new TtEqTool();
        tool.setToolCode(toolRepair.getToolCode());
        tool.setRepairStatus(ToolRepairStatus.NEED_BACK.getCode());
        ttEqToolDao.updateRepairStatusByToolCode(tool);

    }

    private String checkToolRepairStatus(String toolCode) {
        if (StringUtils.isBlank(toolCode))
            return "";
        TtEqTool params = new TtEqTool();
        params.setToolCode(toolCode);
        params.setDelFlag(CommonConstants.DEL_FLAG);
        TtEqTool tool = ttEqToolDao.selectOne(params);
        if (tool == null) {
            return "";
        }
        return tool.getRepairStatus();
    }
}
